<!--
 * @Description:
 * @Author: ZachGmy
 * @Date: 2022-06-28 15:09:37
 * @LastEditors: DaarkCaat 1250178758@qq.com
 * @LastEditTime: 2023-01-04 21:53:16
-->
<template>
  <div>
    <!-- 头部功能按钮区域 -->
    <div class="headArea">
      <!-- 新增按钮 -->
      <el-button class="addBtn" type="primary" @click="addNews">新增</el-button>
      <div class="searchArea">
        <!-- 搜索输入框 -->
        <el-input style="margin:auto 1%;" placeholder="请输入内容" v-model="searchStr" clearable>
        </el-input>
        <!-- 搜索按钮 -->
        <el-button type="primary" @click="getNewsData">搜索</el-button>
      </div>
    </div>
    <!-- 新增新闻模态框 -->
    <el-dialog :title="dialogTittle" :visible.sync="dialogVisible" width="70%">
      <!-- 表单开始区域 -->
      <el-form ref="newsForm" :model="newsForm" :rules="newsRules" label-width="80px">
        <!-- 新闻名称 -->
        <el-form-item label="新闻名称" prop="title">
          <el-input v-model="newsForm.title"></el-input>
        </el-form-item>
        <!-- 新闻分类 -->
        <el-form-item label="新闻分类" prop="categoryId">
          <el-select v-model="newsForm.categoryId" placeholder="请选择活动区域">
            <!--
              label 展示给用户看的数据
              value 是传递到后端的参数
             -->
            <el-option v-for="item in categoryData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 资讯详情 -->
        <el-form-item label="资讯详情" prop="content">
          <!-- 富文本编辑器 -->
          <vue-tinymce v-model="newsForm.content" :setting="setting" />
        </el-form-item>
      </el-form>
      <!-- 表单结束区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit('newsForm')">提 交</el-button>
      </span>
    </el-dialog>
    <!-- 新闻信息展示页面 -->
    <el-table :data="newsData" style="width: 100%">
      <!-- 序号 -->
      <el-table-column type="index" label="序号" align="center">
      </el-table-column>
      <!-- 新闻标题 -->
      <el-table-column prop="title" label="新闻标题" align="center">
      </el-table-column>
      <!-- 新闻类型 -->
      <el-table-column prop="categoryName" label="新闻类型" align="center">
      </el-table-column>
      <!-- 新闻发布时间 -->
      <el-table-column prop="uploadTime" label="发布时间" align="center">
      </el-table-column>
      <!-- 新闻审核状态 -->
      <el-table-column prop="status" label="审核状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusClass(scope.row.status)" disable-transitions>{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="editNewsData(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandler(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页操作栏 -->
    <div class="page">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage2" :page-sizes="[2, 4, 6, 8, 10]" :page-size="pageSize"
        layout="sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
// 引入axios
import { get } from "../../utils/request";
import { post } from "../../utils/request";
import moment from "moment";
export default {
  data() {
    return {
      // 控制模态框的显示与隐藏
      dialogVisible: false,
      // 对话框标题
      dialogTittle: "",
      // 要提交的表单对象
      newsForm: {},
      // 所有栏目的数组
      categoryData: [],
      // 富文本编辑器的配置
      setting: {
        menubar: false,
        toolbar:
          "undo redo | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image media table | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | indent outdent | superscript subscript | removeformat |",
        toolbar_drawer: "sliding",
        quickbars_selection_toolbar:
          "removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor",
        plugins: "link image media table lists fullscreen quickbars",
        language: "zh_CN", //本地化设置
        height: 350,

      },
      // 搜索字符串
      searchStr: '',
      // 新闻数据对象
      newsData: [],
      // 新闻数据参数验证
      newsRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
        ],
        categoryId: [
          { required: true, message: '请选择新闻分类', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' },
        ],
      },
      // 分页数组数据对象
      page: 1,
      pageSize: 10,
      total: 10,

    };
  },
  created() {
    // 页面加载时
    // 自动获取所有栏目的数据
    this.getCategoryData();
    // 自动获取所有新闻数据
    this.getNewsData();
  },
  methods: {
    // 获取所有分类的数据
    async getCategoryData() {
      let res = await get("/category/findAll");
      // console.log(res);
      this.categoryData = res.data;
    },

    // 分页获取新闻列表信息
    async getNewsData() {
      let params = {
        page: this.page,
        pageSize: this.pageSize,
        title: this.searchStr,
      };
      // 发送请求
      let res = await get("/article/pageQuery", params)
      // 绑定数据
      this.newsData = res.data.list.map(item => {
        return {
          id: item.id,
          title: item.title,
          content: item.content,
          categoryId: item.category.id,
          categoryName: item.category.name,
          uploadTime: moment(item.publishTime).format("YYYY-MM-DD HH:mm:ss"),
          status: item.status,
        }
      })
      this.page = res.data.page
      this.pageSize = res.data.pageSize
      this.total = res.data.total
    },
    // 返回状态标签样式方法
    getStatusClass(status) {
      switch (status) {
        case '未审核': return 'info'
        case '审核不通过': return 'danger'
        case '审核通过': return ''
        case '推荐': return 'success'
        default: return ''
      }
    },

    // 发布新闻弹出对话框
    addNews() {
      this.dialogTittle = "发布新的新闻";
      this.newsForm = {};
      this.dialogVisible = true;
    },
    // 修改新闻方法
    editNewsData(row) {
      this.dialogTittle = "修改已发布的新闻";
      // 绑定需要修改的数据
      this.newsForm = row;
      this.newsForm.categoryId = row.categoryId;
      this.newsForm.content = row.content;
      this.dialogVisible = true;
    },
    // 删除新闻方法
    deleteHandler(id) {
      this.$confirm("此操作将永久该新闻信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        // 点击确定时  执行的是.then
        .then(() => {
          // 在点击确定按钮的代码块中发送删除的请求
          get("/article/deleteById", { id }).then((res) => {
            // 提示删除成功
            this.$message({
              type: "success",
              message: res.message,
            });
            // 1.计算出当前数据的总页数
            // 向上取整 Math.ceil()
            let totalPage = Math.ceil((this.total - 1) / this.pageSize)
            // console.log(totalPage);
            // 2.如果该数据是当前页的最后一条数据 那么删除成功之后就查询上一页的数据
            let currentPage = this.page > totalPage ? totalPage : this.page
            // 3.如果当前只剩下一页 就显示第一页就可以了
            this.page = currentPage < 1 ? 1 : currentPage
            // 刷新当前的页面数据
            this.getNewsData()
          });
        })
        // 点击取消的时候  指向的是.catch
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 提交更改方法，按钮提交数据对象名
    submit(newsFormName) {
      // 验证表单内容
      this.$refs[newsFormName].validate((valid) => {
        if(valid){
          // 设置上传的参数
          let uploadData = this.newsForm;
          // uploadData.id = this.newsForm.id;
          // uploadData.title = this.newsForm.title;
          // uploadData.content = this.newsForm.content;
          // uploadData.categoryId = this.newsForm.categoryId;

          // 发送请求
          post("/article/saveOrUpdate", uploadData).then((res) => {
            // 成功提示
            this.$message({
              message: res.message,
              type: "success",
            });
             // 刷新当前页面的数据
             this.getNewsData();
            // 清空表单对象
            this.newsForm = {};
            // 关闭模态框
            this.dialogVisible = false;
          });
        }
        else {
          console.log("error submit!!");
          return false;
        }
      });
    },


    // 分页参数改变事件
    handleSizeChange(val) {
      this.pageSize = val;
      this.getNewsData();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getNewsData();
    },
  },
};
</script>

<style scoped>
/* 头部功能按钮区域 */
.headArea {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

/* 搜索区域样式 */
.searchArea {
  display: flex;
}

/* 分页操作栏样式 */
.page{
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>
